package com.auto.learning.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.adapter.LichengBooklistAdapter;
import com.auto.learning.adapter.PaihangAdapter;
import com.auto.learning.bean.BookBean;
import com.auto.learning.bean.PaihangBean;
import com.auto.learning.bean.ReadLichengBean;
import com.auto.learning.bean.ResponeResult;
import com.auto.learning.event.Handle;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.pay.UserBuyUtils;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.service.MyUserInfo;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.tools.CommonMethod;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.RoundImageView;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.SharedPreferencesUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

public class ReadBookLiChengActivity extends Activity implements Callback {
	public final static int GETUSERINFO_SUCCESS = 1; 
	public final static int GETMYREADBOOK_SUCCESS = 2; 
	public final static int GETMYREADBOOK_FAIL = 3; 
	private ArrayList<BookBean> list = new ArrayList<BookBean>();
	
	private TextView tv_other,tv_china,tv_usa,tv_eur,tv_username,tv_grade,tv_has_read,tv_jinji,tv_no_data_tip,tv_no_data_tip_2;
	private ImageView fg_me_userpic,image_share,image_backgroup,image_phb_top,image_up,imageView1;
	private RoundImageView image_face;
	private ListView listview_paim;
	private PaihangAdapter adapter;
	private LichengBooklistAdapter lichengBooklistAdapter;
	private GridView gv_booklist;
	ArrayList<PaihangBean> pList = new ArrayList<PaihangBean>();
	private LinearLayout linear_bottom,activity_base_back,activity_base_title;
	private PullToRefreshScrollView scrollview;
	private ScrollView m_Scrollview;
	private int pageSize = 9;
	private int pageIndex = 0;
	
	private Handle handle = new Handle(this){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case HttpRequestHelper.GETDATA_SUCCESS:
				ResponeResult responeResult = (ResponeResult) msg.obj;
				if (responeResult != null) {
					ArrayList<PaihangBean> m_list = new Gson().fromJson(responeResult.getData(), new TypeToken<ArrayList<PaihangBean>>(){}.getType());
					if (pList != null) {
						pList.clear();
						pList.addAll(m_list);
						if (adapter != null) {
							adapter.notifyDataSetChanged();
						}
						CommonMethod.setListViewHeight(listview_paim);
						m_Scrollview.smoothScrollTo(0, 0);
					}
				}
				break;
			case GETMYREADBOOK_SUCCESS:
				ResponeResult read_responeResult = (ResponeResult) msg.obj;
				if (read_responeResult != null) {
					ArrayList<BookBean> r_list = new Gson().fromJson(read_responeResult.getData(), new TypeToken<ArrayList<BookBean>>(){}.getType());
					if (list != null) {
						if (pageIndex == 0) {
							list.clear();
							list.addAll(r_list);
						}else {
							list.addAll(r_list);
						}
						if (r_list.size() >= 9) {
							pageIndex ++;
							scrollview.setMode(Mode.PULL_UP_TO_REFRESH);
						} else {
							scrollview.setMode(Mode.DISABLED);
							tv_no_data_tip.setVisibility(View.VISIBLE);
						}
						if (scrollview != null) {
							scrollview.onRefreshComplete();
						}
						if (lichengBooklistAdapter != null) {
							lichengBooklistAdapter.notifyDataSetChanged();
						}
						if (list != null && list.size() == 0) {
							tv_no_data_tip.setVisibility(View.GONE);
							tv_no_data_tip_2.setVisibility(View.VISIBLE);
						}else {
							tv_no_data_tip_2.setVisibility(View.GONE);
						}
						CommonMethod.setGridViewHeight(gv_booklist, 3, CommonMethod.dip2px(ReadBookLiChengActivity.this, 8));
					}
				}
				break;
			case GETMYREADBOOK_FAIL:
				CommonMethod.makeNotice(ReadBookLiChengActivity.this, msg.obj.toString());
				if (scrollview != null) {
					scrollview.onRefreshComplete();
				}
				break;
			case GETUSERINFO_SUCCESS:
				ResponeResult readlicheng_Result = (ResponeResult) msg.obj;
				if (readlicheng_Result != null) {
					ReadLichengBean lichengBean = new Gson().fromJson(readlicheng_Result.getData(), new TypeToken<ReadLichengBean>(){}.getType());
					showData(lichengBean);
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_licheng);
		initView();
		initImageLoader();
		getUserReadInfo();
		getPaihangData();
		getMyReadBookData();
		TemporaryVariable.activities.push(this);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		TemporaryVariable.activities.removeElement(this);
		super.onDestroy();
	}
	
	private void initView(){
		tv_no_data_tip_2 = (TextView) findViewById(R.id.tv_no_data_tip_2);
		tv_no_data_tip = (TextView) findViewById(R.id.tv_no_data_tip);
		image_backgroup = (ImageView) findViewById(R.id.image_backgroup);
		image_phb_top = (ImageView) findViewById(R.id.image_phb_top);
		image_phb_top.setVisibility(View.GONE);
		imageView1 = (ImageView) findViewById(R.id.imageview1);
		imageView1.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.dengjibackground));
		image_phb_top.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.mydsb));
		tv_username = (TextView) findViewById(R.id.tv_username);
		tv_grade = (TextView) findViewById(R.id.tv_grade);
		tv_has_read = (TextView) findViewById(R.id.tv_has_read);
		tv_jinji = (TextView) findViewById(R.id.tv_jinji);
		image_up = (ImageView) findViewById(R.id.image_up);
		image_face = (RoundImageView) findViewById(R.id.image_face);
		image_face.setType(RoundImageView.TYPE_ROUND);
		image_backgroup.setImageBitmap(CommonMethod.readBitMap(this, R.drawable.phbbg));
		image_share = (ImageView) findViewById(R.id.image_share);
		image_share.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				int userId = (int) SharedPreferencesUtils.getParam(ReadBookLiChengActivity.this, HttpRequestHelper.USERID, 0);
				if (userId == 0) {
					return;
				}
				String url = HttpCommonInfo.MURL +"user-share?userId=" + userId +"&more=1";
				String userName = MyUserInfo.getInstance().getUserInfoBean().getLoginName();
				String title = String.format(getResources().getString(R.string.text_share_splash_title), TextUtils.isEmpty(userName) ? "" :userName + "的");
				new ShareView(ReadBookLiChengActivity.this, ReadBookLiChengActivity.this).setTitle(title).setUrl(url).setContent(getResources().getString(R.string.text_share_splash_content)).setType(1).show(findViewById(R.id.relative_main));
			}
		});
		scrollview = (PullToRefreshScrollView) findViewById(R.id.scrollview2);
		scrollview.setMode(Mode.DISABLED);
		scrollview.setScrollingWhileRefreshingEnabled(true);
		m_Scrollview = scrollview.getRefreshableView();
		scrollview.setOnRefreshListener(new OnRefreshListener2<ScrollView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
				
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
				getMyReadBookData();
			}
		});
		tv_china = (TextView) findViewById(R.id.tv_china);
		tv_other = (TextView) findViewById(R.id.tv_other);
		tv_usa = (TextView) findViewById(R.id.tv_usa);
		tv_eur = (TextView) findViewById(R.id.tv_eur);
		activity_base_title = (LinearLayout) findViewById(R.id.activity_base_title);
		activity_base_title.setVisibility(View.VISIBLE);
		
		linear_bottom = (LinearLayout) findViewById(R.id.linear_read_a);
		linear_bottom.setVisibility(View.GONE);
		activity_base_back = (LinearLayout) findViewById(R.id.activity_base_back);
		activity_base_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		
		listview_paim = (ListView) findViewById(R.id.listview_paim);
		adapter = new PaihangAdapter(this, pList);
		listview_paim.setAdapter(adapter);
		
		gv_booklist = (GridView) findViewById(R.id.gv_booklist);
		lichengBooklistAdapter = new LichengBooklistAdapter(this,list);
		gv_booklist.setAdapter(lichengBooklistAdapter);
		gv_booklist.setSelector(new ColorDrawable(Color.TRANSPARENT));
		
		gv_booklist.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
				/*handle.postDelayed(new Runnable() {
					public void run() {
						MusicPlayManager.getInstance(ReadBookLiChengActivity.this).setPlayList(list).setBookId(list.get(position).getBookId()).play();
					}
				}, 1500);
				Intent intent = new Intent(ReadBookLiChengActivity.this, PlayActivity.class);
				intent.putExtra("bookId", list.get(position).getBookId());
				intent.putExtra("faceImg", TextUtils.isEmpty(list.get(position).getFaceImg()) ? "" : list.get(position).getFaceImg());
				startActivity(intent);*/
				
				if( list.get(position).getNeedBuy() == 2 && !TemporaryVariable.downLoadedList.contains(list.get(position).getBookId())){
					
						new UserBuyUtils((ReadBookLiChengActivity.this), list.get(position).getBookId(), list.get(position).getPriceTag(),list.get(position).getBookName()).buy();
					
					return;
				}
				playDialog(list.get(position));
			}
		});
		
	}
	
	
	
	/**
	 * 书单
	 */
	private void getMyReadBookData(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		params.add(new BasicNameValuePair(HttpRequestHelper.PAGE_INDEX, String.valueOf(pageIndex)));
		params.add(new BasicNameValuePair("pageSize", String.valueOf(pageSize)));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.MY_READ_BOOK, params, handle, GETMYREADBOOK_SUCCESS,GETMYREADBOOK_FAIL);
	}
	
	/**
	 * 排行版
	 */
	private void getPaihangData(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.USER_RANK_LIST, params, handle, HttpRequestHelper.GETDATA_SUCCESS);
	}
	
	/**
	 * 用户读书信息
	 */
	private void getUserReadInfo(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(HttpRequestHelper.USERID, String.valueOf(SharedPreferencesUtils.getParam(this, HttpRequestHelper.USERID, 0))));
		HttpRequestHelper.executeHttpData(this, HttpRequestHelper.USER_READ_INFO, params, handle, GETUSERINFO_SUCCESS);
	}
	
	private void showData(ReadLichengBean lichengBean){
		tv_china.setText(lichengBean.getCnBookNum()+"本");
		tv_usa.setText(lichengBean.getUsaBookNum()+"本");
		tv_eur.setText(lichengBean.getEurBookNum()+"本");
		tv_other.setText(lichengBean.getOtherBookNum()+"本");
		ImageLoader.getInstance().displayImage(lichengBean.getFaceUrl(), image_face, options);
		tv_username.setText(lichengBean.getUserName()+"");
		tv_grade.setText(lichengBean.getUserGrade()+"");
		tv_has_read.setText(String.format("已读%s本", lichengBean.getBookNum()+""));
		if (lichengBean.getNeedNum() == 0) {
			tv_jinji.setText(String.format("已最高等级"));
			image_up.setVisibility(View.GONE);
		}else {
			tv_jinji.setText(String.format("+%s晋级", lichengBean.getNeedNum()+""));
			image_up.setVisibility(View.VISIBLE);
		}
	}
	
	DisplayImageOptions options;
	private void initImageLoader(){
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.me_user)
		.showImageForEmptyUri(R.drawable.me_user)
		.showImageOnFail(R.drawable.me_user).cacheInMemory(true)
		.cacheOnDisk(true).considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(ReadBookLiChengActivity.this, msg);
		return false;
	}
	
	
	public void showDialog(final BookBean bookBean){
		CommonAlertDialog alertDialog = new CommonAlertDialog(ReadBookLiChengActivity.this);
		alertDialog.setTextMessage(String.format(getResources().getString(R.string.play_size_notice), CommonMethod.calculationNum(bookBean.getProSize() + bookBean.getDoubiSize() + bookBean.getEnSize())));
		alertDialog.setShowTitle(true);
		String[] a = {getResources().getString(R.string.app_continue),getResources().getString(R.string.app_cancel)};
		alertDialog.setBtns(new DialogListener() {
			
			@Override
			public void okButtonClick(Dialog dialog) {
				play(bookBean);
				MusicPlayManager.getInstance(ReadBookLiChengActivity.this).setShowNetTips(false);
				dialog.dismiss();
			}

			@Override
			public void cancelButtonClick(Dialog dialog) {
				dialog.dismiss();
				CommonMethod.reordPlayStatus(ReadBookLiChengActivity.this, bookBean.getBookId(), true);
			}

			@Override
			public void otherButtonClick(Dialog dialog) {
				CommonMethod.reordPlayStatus(ReadBookLiChengActivity.this, bookBean.getBookId(), true);
				dialog.dismiss();
			}
		},a);
		alertDialog.show();
	}

	
	public void playDialog(final BookBean bookBean){
		if (TemporaryVariable.downLoadedList.contains(bookBean.getBookId())) {
			play(bookBean);
		}else {
			if ((boolean)SharedPreferencesUtils.getParam(ReadBookLiChengActivity.this, HttpRequestHelper.DWONLOAD_PLAY_CONTINUE, false)) {
				play(bookBean);
			} else {
				switch (CommonMethod.getNetworkState(ReadBookLiChengActivity.this)) {
				case 0:
					CommonMethod.makeNotice(ReadBookLiChengActivity.this, getResources().getString(R.string.connect_err_io));
					break;
				case 1:
					play(bookBean);
					break;
				case 2:
					showDialog(bookBean);
					break;
				}
			}
		}
	}
	
	
	private void play(final BookBean bookBean){
		handle.postDelayed(new Runnable() {
			public void run() {
				ArrayList<BookBean> m_list = new ArrayList<BookBean>();
				m_list.add(bookBean);
				
//				if (CommonMethod.getNetworkState(ReadBookLiChengActivity.this) == 1) {
//					m_list.addAll(list);
				/*}else {
					m_list.add(bookBean);
					int index = list.indexOf(bookBean);
					for (int k = index - 1; k >= 0; k-- ) {
						if (TemporaryVariable.downLoadedList.contains(list.get(k).getBookId())) {
							m_list.add(0,list.get(k));
						} else {
							break;
						}
					}
					for (int i = index + 1; i < list.size(); i++) {
						if (TemporaryVariable.downLoadedList.contains(list.get(i).getBookId())) {
							m_list.add(list.get(i));
						} else {
							break;
						}
					}
				}*/
				MusicPlayManager.getInstance(ReadBookLiChengActivity.this).setPlayList(m_list).setBookId(bookBean.getBookId()).play();
			}
		}, 1500);
		TemporaryVariable.read_list.clear();
		for (int i = 0; i < list.size(); i++) {
			TemporaryVariable.read_list.add(list.get(i).getBookId());
		}
		Intent intent = new Intent(ReadBookLiChengActivity.this, PlayActivity.class);
		intent.putExtra("bookId", bookBean.getBookId());
		intent.putExtra("faceImg", bookBean.getFaceImg());
		intent.putExtra("canRead",bookBean.getCanRead());
		intent.putExtra("needBuy", bookBean.getNeedBuy());
		startActivity(intent);
	}
	
}
